<template>
  <div class="farm-market-page">
    
    <!-- 顶部导航 -->
    <header class="market-header">
      <div class="header-container">
        <div class="logo-section">
          <h1 class="logo">农产品商城</h1>
          <p class="slogan">从农场到餐桌，新鲜直达</p>
        </div>
        
        <div class="search-section">
          <el-input
            v-model="searchText"
            placeholder="搜索农产品或农夫UID..."
            class="search-input"
            size="large"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="user-actions">
          <el-badge :value="cartCount" class="cart-badge">
            <el-button 
              type="primary" 
              circle 
              size="large"
              @click="showCart = true"
              class="cart-btn"
            >
              <el-icon><ShoppingCart /></el-icon>
            </el-button>
          </el-badge>
        </div>
      </div>
    </header>

    <!-- 轮播图 -->
    <section class="banner-section">
      <div class="banner-container">
        <el-carousel 
          height="400px" 
          :interval="4000" 
          indicator-position="outside"
          class="hot-product-carousel"
        >
          <el-carousel-item v-for="product in hotProducts" :key="product.id">
            <div class="carousel-item" @click="handleCarouselClick(product)">
              <img :src="product.image" :alt="product.name" class="carousel-image" />
              <div class="carousel-content">
                <div class="carousel-badge">热门推荐</div>
                <h2 class="carousel-title">{{ product.name }}</h2>
                <p class="carousel-desc">{{ product.description }}</p>
                <div class="carousel-price">
                  <span v-if="product.isPromotion" class="original-price">¥{{ product.originalPrice }}</span>
                  <span class="current-price">¥{{ product.currentPrice }}</span>
                </div>
                <el-button type="primary" size="large" class="carousel-btn">
                  <el-icon><ShoppingCart /></el-icon>
                  立即购买
                </el-button>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
    </section>

    <!-- 超级菜单导航 -->
    <nav class="super-menu-nav">
      <div class="nav-container">
        <!-- 一级菜单 -->
        <div class="menu-level-1">
          <div
            v-for="category in level1Categories"
            :key="category.value"
            class="menu-item-wrapper"
          >
            <el-button
              :type="activeLevel1 === category.value ? 'primary' : 'default'"
              size="large"
              @click="handleLevel1Click(category)"
              class="menu-btn level-1-btn"
            >
              <span class="btn-icon">{{ category.icon }}</span>
              {{ category.label }}
              <el-icon class="arrow-icon">
                <ArrowDown v-if="activeLevel1 === category.value" />
                <ArrowRight v-else />
              </el-icon>
            </el-button>
            
            <!-- 树形选择器 -->
            <div 
              v-if="activeLevel1 === category.value && category.children" 
              class="tree-selector-container"
            >
              <el-tree-select
                v-model="selectedCategories"
                :data="category.children"
                multiple
                :render-after-expand="false"
                check-strictly
                check-on-click-node
                placeholder="请选择子分类"
                class="category-tree-select"
                @change="handleTreeSelectChange"
              />
            </div>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="content-container">
        <!-- 面包屑导航 -->
        <div class="breadcrumb" v-if="currentCategoryPath.length > 0">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item 
              v-for="(item, index) in currentCategoryPath" 
              :key="index"
              @click="handleBreadcrumbClick(index)"
              class="breadcrumb-item"
            >
              {{ item.label }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!-- 产品网格 -->
        <section class="products-section">
          <h2 class="section-title" v-if="currentCategoryPath.length > 0">
            {{ currentCategoryPath[currentCategoryPath.length - 1].label }}
          </h2>
          <h2 class="section-title" v-else>推荐产品</h2>

          <div v-if="filteredProducts.length === 0" class="empty-state">
            <div class="empty-icon">📦</div>
            <p class="empty-text">暂无相关产品</p>
            <el-button type="primary" @click="clearFilters">查看全部产品</el-button>
          </div>

          <div v-else class="products-grid">
            <div
              v-for="product in filteredProducts"
              :key="product.id"
              class="product-card"
              :class="{ 'promotion-card': product.isPromotion }"
            >
              <!-- 促销标签 -->
              <div v-if="product.isPromotion" class="promotion-badge">
                <span class="badge-text">特价</span>
              </div>

              <!-- 产品图片 -->
              <div class="product-image">
                <img :src="product.image" :alt="product.name" />
                <div class="image-overlay">
                  <el-button 
                    type="primary" 
                    circle 
                    size="large"
                    @click="addToCart(product)"
                    class="quick-add-btn"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-button>
                </div>
              </div>

              <!-- 产品信息 -->
              <div class="product-info">
                <div class="product-header">
                  <h3 class="product-name">{{ product.name }}</h3>
                  <div class="product-rating">
                    <el-rate
                      v-model="product.rating"
                      disabled
                      size="small"
                    />
                    <span class="rating-text">{{ product.rating }}</span>
                  </div>
                </div>
                
                <p class="product-desc">{{ product.description }}</p>
                
                <div class="product-meta">
                  <div class="meta-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ product.origin }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Scale /></el-icon>
                    <span>{{ product.weight }}</span>
                  </div>
                </div>

                <div class="price-section">
                  <span v-if="product.isPromotion" class="original-price">
                    ¥{{ product.originalPrice }}
                  </span>
                  <span class="current-price">¥{{ product.currentPrice }}</span>
                </div>

                <div class="product-actions">
                  <el-button 
                    type="primary" 
                    class="add-cart-btn"
                    @click="addToCart(product)"
                  >
                    <el-icon><ShoppingCart /></el-icon>
                    加入购物车
                  </el-button>
                  <el-button 
                    class="detail-btn"
                    @click="showProductDetail(product)"
                  >
                    查看详情
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </main>

    <!-- 产品详情弹窗 -->
    <el-dialog
      v-model="showDetail"
      :title="selectedProduct?.name"
      width="900px"
      align-center
      class="product-detail-dialog"
    >
      <div v-if="selectedProduct" class="product-detail-content">
        <!-- 产品信息 -->
        <div class="product-detail-main">
          <div class="product-gallery">
            <img :src="selectedProduct.image" :alt="selectedProduct.name" class="main-image" />
          </div>
          
          <div class="product-detail-info">
            <h2 class="product-title">{{ selectedProduct.name }}</h2>
            <div class="product-rating-large">
              <el-rate
                v-model="selectedProduct.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
              />
              <span class="review-count">128 条评价</span>
            </div>
            
            <div class="price-section-large">
              <span v-if="selectedProduct.isPromotion" class="original-price-large">
                ¥{{ selectedProduct.originalPrice }}
              </span>
              <span class="current-price-large">¥{{ selectedProduct.currentPrice }}</span>
              <span v-if="selectedProduct.isPromotion" class="discount-tag">
                省{{ calculateDiscount(selectedProduct) }}%
              </span>
            </div>
            
            <div class="product-specs">
              <div class="spec-item">
                <span class="spec-label">产地：</span>
                <span class="spec-value">{{ selectedProduct.origin }}</span>
              </div>
              <div class="spec-item">
                <span class="spec-label">规格：</span>
                <span class="spec-value">{{ selectedProduct.weight }}</span>
              </div>
              <div class="spec-item">
                <span class="spec-label">配送：</span>
                <span class="spec-value">24小时内发货</span>
              </div>
            </div>
            
            <div class="product-actions-large">
              <el-button type="primary" size="large" @click="addToCart(selectedProduct)" class="buy-btn">
                <el-icon><ShoppingCart /></el-icon>
                加入购物车
              </el-button>
              <el-button type="success" size="large" @click="handleQuickBuy(selectedProduct)" class="quick-buy-btn">
                立即购买
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 农夫信息 -->
        <div class="farmer-section">
          <h3 class="section-title">农户信息</h3>
          <div class="farmer-card">
            <div class="farmer-avatar">
              <img :src="selectedProduct.farmer.avatar" :alt="selectedProduct.farmer.username" />
            </div>
            <div class="farmer-info">
              <div class="farmer-name">{{ selectedProduct.farmer.username }}</div>
              <div class="farmer-stats">
                <div class="stat-item">
                  <span class="stat-label">UID:</span>
                  <span class="stat-value">{{ selectedProduct.farmer.uid }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">联系方式:</span>
                  <span class="stat-value">{{ selectedProduct.farmer.phone }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">种植经验:</span>
                  <span class="stat-value">{{ selectedProduct.farmer.experience }}年</span>
                </div>
              </div>
              <div class="farmer-desc">
                专业种植{{ selectedProduct.name }}，坚持有机种植，保证产品品质
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 购物车抽屉 -->
    <el-drawer v-model="showCart" title="购物车" size="400px">
      <div class="cart-content">
        <div v-if="cartItems.length === 0" class="empty-cart">
          <div class="empty-cart-icon">
            <el-icon><ShoppingCart /></el-icon>
          </div>
          <p class="empty-cart-text">购物车空空如也</p>
          <el-button type="primary" @click="showCart = false">继续购物</el-button>
        </div>
        <div v-else>
          <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <img :src="item.image" :alt="item.name" class="cart-item-image" />
            <div class="cart-item-info">
              <h4 class="cart-item-name">{{ item.name }}</h4>
              <p class="cart-item-price">¥{{ item.price }}</p>
            </div>
            <div class="cart-item-actions">
              <el-button 
                size="small" 
                circle 
                @click="updateQuantity(item, -1)"
                class="quantity-btn"
              >
                <el-icon><Minus /></el-icon>
              </el-button>
              <span class="quantity-display">{{ item.quantity }}</span>
              <el-button 
                size="small" 
                circle 
                @click="updateQuantity(item, 1)"
                class="quantity-btn"
              >
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
          </div>
          <div class="cart-total">
            <div class="total-line">
              <span>商品总价:</span>
              <span>¥{{ cartTotal }}</span>
            </div>
            <div class="total-line main-total">
              <span>实付金额:</span>
              <span class="final-price">¥{{ cartTotal }}</span>
            </div>
          </div>
          <el-button type="primary" class="checkout-btn" size="large" @click="navigateTo('/buyer/payFor')">
            立即结算 (¥{{ cartTotal }})
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 页脚 -->
    <footer class="market-footer">
      <div class="footer-container">
        <div class="footer-content">
          <div class="footer-section">
            <h3 class="footer-title">农产品商城</h3>
            <p class="footer-desc">致力于为您提供最新鲜、最优质的农产品</p>
          </div>
          <div class="footer-section">
            <h4 class="footer-subtitle">购物指南</h4>
            <ul class="footer-links">
              <li><a href="#" class="footer-link">购物流程</a></li>
              <li><a href="#" class="footer-link">会员介绍</a></li>
              <li><a href="#" class="footer-link">常见问题</a></li>
            </ul>
          </div>
          <div class="footer-section">
            <h4 class="footer-subtitle">配送方式</h4>
            <ul class="footer-links">
              <li><a href="#" class="footer-link">上门自提</a></li>
              <li><a href="#" class="footer-link">211限时达</a></li>
              <li><a href="#" class="footer-link">配送服务查询</a></li>
            </ul>
          </div>
          <div class="footer-section">
            <h4 class="footer-subtitle">售后服务</h4>
            <ul class="footer-links">
              <li><a href="#" class="footer-link">售后政策</a></li>
              <li><a href="#" class="footer-link">价格保护</a></li>
              <li><a href="#" class="footer-link">退款说明</a></li>
            </ul>
          </div>
        </div>
        <div class="footer-bottom">
          <p>&copy; 2025 农产品融销一体化商城.</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

// 导入图标
import {
  ShoppingCart,
  Plus,
  Minus,
  Location,
  ScaleToOriginal as Scale,
  Search,
  ArrowDown,
  ArrowRight
} from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 完整的分类数据结构
const categoryData = {
  grain: {
    label: '粮食作物',
    icon: '🌾',
    children: {
      cereal: {
        label: '谷物',
        icon: '🌽',
        children: [
          { value: 'rice', label: '水稻' },
          { value: 'wheat', label: '小麦' },
          { value: 'corn', label: '玉米' },
          { value: 'barley', label: '大麦' },
          { value: 'oats', label: '燕麦' },
          { value: 'sorghum', label: '高粱' },
          { value: 'millet', label: '小米' },
          { value: 'buckwheat', label: '荞麦' }
        ]
      },
      legume: {
        label: '豆类',
        icon: '🫘',
        children: [
          { value: 'soybean', label: '大豆' },
          { value: 'mungbean', label: '绿豆' },
          { value: 'redbean', label: '红豆' },
          { value: 'blackbean', label: '黑豆' },
          { value: 'broadbean', label: '蚕豆' },
          { value: 'pea', label: '豌豆' },
          { value: 'kidneybean', label: '芸豆' }
        ]
      },
      tuber: {
        label: '薯类',
        icon: '🍠',
        children: [
          { value: 'potato', label: '马铃薯' },
          { value: 'sweetpotato', label: '甘薯' },
          { value: 'cassava', label: '木薯' },
          { value: 'yam', label: '山药' }
        ]
      }
    }
  },
  oil: {
    label: '油料作物',
    icon: '🥜',
    children: [
      { value: 'rape', label: '油菜' },
      { value: 'peanut', label: '花生' },
      { value: 'sunflower', label: '向日葵' },
      { value: 'sesame', label: '芝麻' },
      { value: 'oiltea', label: '油茶' }
    ]
  },
  vegetable: {
    label: '蔬菜',
    icon: '🥬',
    children: {
      rootveg: {
        label: '根菜类',
        icon: '🥕',
        children: [
          { value: 'radish', label: '萝卜' },
          { value: 'carrot', label: '胡萝卜' },
          { value: 'sweetpotato', label: '甘薯' },
          { value: 'potato', label: '马铃薯' }
        ]
      },
      leafveg: {
        label: '叶菜类',
        icon: '🥬',
        children: [
          { value: 'cabbage', label: '白菜' },
          { value: 'spinach', label: '菠菜' },
          { value: 'lettuce', label: '生菜' },
          { value: 'rape', label: '油菜' },
          { value: 'chive', label: '韭菜' }
        ]
      },
      stemveg: {
        label: '茎菜类',
        icon: '🎋',
        children: [
          { value: 'celery', label: '芹菜' },
          { value: 'asparagus', label: '莴笋' },
          { value: 'bamboo', label: '竹笋' },
          { value: 'lotus', label: '藕' },
          { value: 'onion', label: '洋葱' }
        ]
      },
      flowerveg: {
        label: '花菜类',
        icon: '🥦',
        children: [
          { value: 'cauliflower', label: '花椰菜' },
          { value: 'broccoli', label: '西兰花' },
          { value: 'lily', label: '黄花菜' }
        ]
      },
      fruitveg: {
        label: '果菜类',
        icon: '🍅',
        children: [
          { value: 'tomato', label: '番茄' },
          { value: 'cucumber', label: '黄瓜' },
          { value: 'pepper', label: '辣椒' },
          { value: 'eggplant', label: '茄子' },
          { value: 'pumpkin', label: '南瓜' },
          { value: 'waxgourd', label: '冬瓜' }
        ]
      },
      mushroom: {
        label: '食用菌类',
        icon: '🍄',
        children: [
          { value: 'shiitake', label: '香菇' },
          { value: 'oyster', label: '平菇' },
          { value: 'enoki', label: '金针菇' },
          { value: 'woodear', label: '木耳' },
          { value: 'tremella', label: '银耳' }
        ]
      }
    }
  },
  fruit: {
    label: '水果',
    icon: '🍎',
    children: {
      pome: {
        label: '仁果类',
        icon: '🍐',
        children: [
          { value: 'apple', label: '苹果' },
          { value: 'pear', label: '梨' },
          { value: 'hawthorn', label: '山楂' }
        ]
      },
      stone: {
        label: '核果类',
        icon: '🍑',
        children: [
          { value: 'peach', label: '桃' },
          { value: 'plum', label: '李' },
          { value: 'apricot', label: '杏' },
          { value: 'mume', label: '梅' },
          { value: 'cherry', label: '樱桃' }
        ]
      },
      berry: {
        label: '浆果类',
        icon: '🍇',
        children: [
          { value: 'grape', label: '葡萄' },
          { value: 'strawberry', label: '草莓' },
          { value: 'blueberry', label: '蓝莓' },
          { value: 'kiwi', label: '猕猴桃' },
          { value: 'pomegranate', label: '石榴' }
        ]
      },
      citrus: {
        label: '柑橘类',
        icon: '🍊',
        children: [
          { value: 'citrus', label: '柑橘' },
          { value: 'orange', label: '橙' },
          { value: 'pomelo', label: '柚' },
          { value: 'lemon', label: '柠檬' }
        ]
      },
      melon: {
        label: '瓜果类',
        icon: '🍉',
        children: [
          { value: 'watermelon', label: '西瓜' },
          { value: 'melon', label: '甜瓜' },
          { value: 'hami', label: '哈密瓜' }
        ]
      },
      tropical: {
        label: '热带水果',
        icon: '🍌',
        children: [
          { value: 'banana', label: '香蕉' },
          { value: 'pineapple', label: '菠萝' },
          { value: 'mango', label: '芒果' },
          { value: 'litchi', label: '荔枝' },
          { value: 'longan', label: '龙眼' },
          { value: 'coconut', label: '椰子' }
        ]
      }
    }
  },
  livestock: {
    label: '畜禽产品',
    icon: '🐖',
    children: {
      meat: {
        label: '肉类',
        icon: '🥩',
        children: [
          { value: 'pork', label: '猪肉' },
          { value: 'beef', label: '牛肉' },
          { value: 'mutton', label: '羊肉' },
          { value: 'chicken', label: '鸡肉' },
          { value: 'duck', label: '鸭肉' }
        ]
      },
      egg: {
        label: '蛋类',
        icon: '🥚',
        children: [
          { value: 'chickenEgg', label: '鸡蛋' },
          { value: 'duckEgg', label: '鸭蛋' },
          { value: 'gooseEgg', label: '鹅蛋' },
          { value: 'quailEgg', label: '鹌鹑蛋' }
        ]
      },
      milk: {
        label: '奶类',
        icon: '🥛',
        children: [
          { value: 'milk', label: '牛奶' },
          { value: 'goatMilk', label: '羊奶' }
        ]
      }
    }
  },
  aquatic: {
    label: '水产品',
    icon: '🐟',
    children: {
      fish: {
        label: '鱼类',
        icon: '🎣',
        children: [
          { value: 'tuna', label: '金枪鱼' },
          { value: 'salmon', label: '三文鱼' },
          { value: 'cod', label: '鳕鱼' },
          { value: 'hairtail', label: '带鱼' },
          { value: 'croaker', label: '黄花鱼' }
        ]
      },
      crustacean: {
        label: '甲壳类',
        icon: '🦐',
        children: [
          { value: 'shrimp', label: '虾' },
          { value: 'crab', label: '蟹' }
        ]
      },
      shellfish: {
        label: '贝类',
        icon: '🐚',
        children: [
          { value: 'oyster', label: '牡蛎' },
          { value: 'clam', label: '蛤蜊' },
          { value: 'scallop', label: '扇贝' },
          { value: 'mussel', label: '贻贝' },
          { value: 'abalone', label: '鲍鱼' }
        ]
      }
    }
  }
}

// 农夫数据
const farmers = ref([
  {
    uid: 'F1001',
    username: '张大山',
    phone: '13800138001',
    avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&h=100&fit=crop&crop=face',
    experience: 8
  },
  {
    uid: 'F1002',
    username: '李小花',
    phone: '13800138002',
    avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=100&h=100&fit=crop&crop=face',
    experience: 12
  },
  {
    uid: 'F1003',
    username: '王老五',
    phone: '13800138003',
    avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop&crop=face',
    experience: 15
  }
])

// 热门产品数据（轮播图用）
const hotProducts = ref([
  {
    id: 101,
    name: '特级五常大米',
    description: '黑龙江五常核心产区，有机种植，米香浓郁',
    currentPrice: '32.8',
    originalPrice: '38.8',
    isPromotion: true,
    image: 'https://images.unsplash.com/photo-1445282768818-728615cc910a?w=300&h=200&fit=crop',
    category: ['grain', 'cereal', 'rice'],
    origin: '黑龙江五常',
    weight: '5kg',
    rating: 4.9,
    farmer: farmers.value[0]
  },
  {
    id: 102,
    name: '有机红富士苹果',
    description: '烟台有机苹果，脆甜多汁，果香浓郁',
    currentPrice: '25.6',
    originalPrice: '',
    isPromotion: false,
    image: 'https://images.unsplash.com/photo-1568702846914-96b305d2aaeb?w=800&h=400&fit=crop',
    category: ['fruit', 'pome', 'apple'],
    origin: '山东烟台',
    weight: '3kg',
    rating: 4.8,
    farmer: farmers.value[1]
  },
  {
    id: 103,
    name: '新鲜大闸蟹',
    description: '阳澄湖大闸蟹，膏肥黄满，肉质鲜美',
    currentPrice: '188',
    originalPrice: '228',
    isPromotion: true,
    image: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?w=800&h=400&fit=crop',
    category: ['aquatic', 'crustacean'],
    origin: '江苏阳澄湖',
    weight: '4只装',
    rating: 4.9,
    farmer: farmers.value[2]
  }
])

// 产品数据
const products = ref([
  {
    id: 1,
    name: '五常有机大米',
    description: '产自黑龙江五常的优质有机大米，米粒饱满，口感香糯',
    currentPrice: '25.8',
    originalPrice: '',
    isPromotion: false,
    image: 'https://images.unsplash.com/photo-1546470427-e212d0d553c3?w=300&h=200&fit=crop',
    category: ['grain', 'cereal', 'rice'],
    origin: '黑龙江五常',
    weight: '5kg',
    rating: 4.8,
    farmer: farmers.value[0]
  },
  {
    id: 2,
    name: '新鲜胡萝卜',
    description: '甜脆有机胡萝卜，富含维生素，农家种植',
    currentPrice: '12.5',
    originalPrice: '15',
    isPromotion: true,
    image: 'https://images.unsplash.com/photo-1445282768818-728615cc910a?w=300&h=200&fit=crop',
    category: ['vegetable', 'rootveg', 'carrot'],
    origin: '内蒙古赤峰',
    weight: '2kg',
    rating: 4.7,
    farmer: farmers.value[0]
  },
  {
    id: 3,
    name: '烟台红富士',
    description: '烟台红富士苹果，脆甜多汁，果香浓郁',
    currentPrice: '15.8',
    originalPrice: '',
    isPromotion: false,
    image: 'https://images.unsplash.com/photo-1568702846914-96b305d2aaeb?w=300&h=200&fit=crop',
    category: ['fruit', 'pome', 'apple'],
    origin: '山东烟台',
    weight: '3kg',
    rating: 4.6,
    farmer: farmers.value[1]
  },
  {
    id: 4,
    name: '新鲜菠菜',
    description: '当天采摘新鲜菠菜，鲜嫩可口，营养丰富',
    currentPrice: '8.5',
    originalPrice: '',
    isPromotion: false,
    image: 'https://images.unsplash.com/photo-1576045057995-568f588f82fb?w=300&h=200&fit=crop',
    category: ['vegetable', 'leafveg', 'spinach'],
    origin: '河北张家口',
    weight: '500g',
    rating: 4.5,
    farmer: farmers.value[1]
  },
  {
    id: 5,
    name: '阳澄湖大闸蟹',
    description: '正宗阳澄湖大闸蟹，膏肥黄满，肉质鲜美',
    currentPrice: '188',
    originalPrice: '228',
    isPromotion: true,
    image: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?w=300&h=200&fit=crop',
    category: ['aquatic', 'crustacean'],
    origin: '江苏阳澄湖',
    weight: '4只装',
    rating: 4.9,
    farmer: farmers.value[2]
  },
  {
    id: 6,
    name: '农家土鸡蛋',
    description: '散养土鸡蛋，蛋黄饱满，营养丰富',
    currentPrice: '18.8',
    originalPrice: '25',
    isPromotion: true,
    image: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?w=300&h=200&fit=crop',
    category: ['livestock', 'egg', 'chickenEgg'],
    origin: '河北张家口',
    weight: '30枚',
    rating: 4.6,
    farmer: farmers.value[0]
  }
])

// 响应式数据
const activeLevel1 = ref('')
const selectedCategories = ref([])
const currentCategoryPath = ref([])
const searchText = ref('')
const showDetail = ref(false)
const showCart = ref(false)
const selectedProduct = ref(null)
const cartItems = ref([])

// 计算属性
const level1Categories = computed(() => {
  return Object.entries(categoryData).map(([key, value]) => ({
    value: key,
    label: value.label,
    icon: value.icon,
    children: convertToTreeData(value.children)
  }))
})

const filteredProducts = computed(() => {
  if (selectedCategories.value.length > 0) {
    return products.value.filter(product => 
      selectedCategories.value.some(category => 
        product.category.includes(category)
      )
    )
  }
  
  if (currentCategoryPath.value.length > 0) {
    const targetCategory = currentCategoryPath.value[currentCategoryPath.value.length - 1].value
    return products.value.filter(product => 
      product.category.includes(targetCategory)
    )
  }
  
  if (searchText.value) {
    return products.value.filter(product => 
      product.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      product.description.toLowerCase().includes(searchText.value.toLowerCase()) ||
      product.farmer.uid.includes(searchText.value) ||
      product.farmer.username.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  return products.value
})

const cartCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

const cartTotal = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0).toFixed(2)
})

// 方法
const convertToTreeData = (children) => {
  if (!children) return []
  
  if (Array.isArray(children)) {
    return children
  }
  
  return Object.entries(children).map(([key, value]) => ({
    value: key,
    label: value.label,
    icon: value.icon,
    children: convertToTreeData(value.children)
  }))
}

const handleLevel1Click = (category) => {
  if (activeLevel1.value === category.value) {
    activeLevel1.value = ''
    selectedCategories.value = []
    currentCategoryPath.value = []
  } else {
    activeLevel1.value = category.value
    selectedCategories.value = []
    currentCategoryPath.value = [category]
  }
}

const handleTreeSelectChange = (selectedValues) => {
  if (selectedValues.length === 0) {
    currentCategoryPath.value = currentCategoryPath.value.slice(0, 1)
  } else {
    // 这里可以根据需要更新面包屑路径
    // 简化处理：只显示一级分类和选中的分类数量
    currentCategoryPath.value = [
      currentCategoryPath.value[0],
      { label: `已选择 ${selectedValues.length} 个子分类`, value: 'selected' }
    ]
  }
}

const handleBreadcrumbClick = (index) => {
  currentCategoryPath.value = currentCategoryPath.value.slice(0, index + 1)
  if (index === 0) {
    selectedCategories.value = []
  }
}

const handleCarouselClick = (product) => {
  addToCart(product)
}

const handleQuickBuy = (product) => {
  addToCart(product)
  showDetail.value = false
  showCart.value = true
}

const calculateDiscount = (product) => {
  if (!product.isPromotion) return 0
  const original = parseFloat(product.originalPrice)
  const current = parseFloat(product.currentPrice)
  return Math.round((1 - current / original) * 100)
}

const addToCart = (product) => {
  const existingItem = cartItems.value.find(item => item.id === product.id)
  
  if (existingItem) {
    existingItem.quantity++
  } else {
    cartItems.value.push({
      ...product,
      price: parseFloat(product.currentPrice),
      quantity: 1
    })
  }
  
  ElMessage.success(`已添加 ${product.name} 到购物车`)
}

const updateQuantity = (item, change) => {
  item.quantity += change
  if (item.quantity <= 0) {
    cartItems.value = cartItems.value.filter(cartItem => cartItem.id !== item.id)
  }
}

const showProductDetail = (product) => {
  selectedProduct.value = product
  showDetail.value = true
}

const handleSearch = () => {
  currentCategoryPath.value = []
  selectedCategories.value = []
}

const clearFilters = () => {
  currentCategoryPath.value = []
  selectedCategories.value = []
  searchText.value = ''
  activeLevel1.value = ''
}

// 初始化
onMounted(() => {
  console.log('农产品商城页面初始化完成')
})
</script>

<style scoped>
/* 重置和基础样式 */
.farm-market-page {
  min-height: 100vh;
  background: #f5f5f5;
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 顶部导航 */
.market-header {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  font-size: 24px;
  font-weight: 700;
  color: #1a8754;
  margin: 0;
}

.slogan {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.search-section {
  flex: 1;
  max-width: 400px;
  margin: 0 40px;
}

.search-input {
  width: 100%;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.cart-btn {
  background: #1a8754;
  border: none;
}

.cart-btn:hover {
  background: #156c43;
}

/* 轮播图 */
.banner-section {
  background: linear-gradient(135deg, #1a8754 0%, #156c43 100%);
  padding: 0;
}

.banner-container {
  max-width: 1200px;
  margin: 0 auto;
}

.hot-product-carousel {
  border-radius: 0 0 12px 12px;
  overflow: hidden;
}

.carousel-item {
  position: relative;
  height: 100%;
  cursor: pointer;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-content {
  position: absolute;
  top: 50%;
  right: 80px;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 12px;
  max-width: 400px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.carousel-badge {
  background: #ff4d4f;
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  display: inline-block;
  margin-bottom: 16px;
}

.carousel-title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.2;
}

.carousel-desc {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
}

.carousel-price {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.carousel-price .original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 16px;
}

.carousel-price .current-price {
  font-size: 24px;
  font-weight: 700;
  color: #ff4d4f;
}

.carousel-btn {
  background: #1a8754;
  border: none;
  height: 44px;
  font-size: 16px;
}

.carousel-btn:hover {
  background: #156c43;
}

/* 超级菜单导航 */
.super-menu-nav {
  background: white;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 80px;
  z-index: 999;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.menu-level-1 {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  position: relative;
}

.menu-item-wrapper {
  position: relative;
}

.menu-btn {
  height: 48px;
  padding: 0 20px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
}

.level-1-btn {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
}

.level-1-btn:hover {
  background: #e9ecef;
  border-color: #dee2e6;
}

.level-1-btn.is-primary {
  background: #1a8754;
  border-color: #1a8754;
}

.btn-icon {
  margin-right: 8px;
  font-size: 18px;
}

.arrow-icon {
  margin-left: 8px;
  font-size: 14px;
}

/* 树形选择器容器 */
.tree-selector-container {
  position: absolute;
  top: 100%;
  left: 0;
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 16px;
  min-width: 300px;
  z-index: 100;
  margin-top: 4px;
}

.category-tree-select {
  width: 100%;
}

/* 主内容区 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.content-container {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.breadcrumb {
  margin-bottom: 24px;
}

.breadcrumb-item {
  cursor: pointer;
  color: #1a8754;
}

.breadcrumb-item:hover {
  color: #156c43;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
  text-align: center;
}

/* 产品网格 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

.product-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.promotion-card {
  border-color: #ff4d4f;
}

.promotion-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #ff4d4f;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  z-index: 2;
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-card:hover .image-overlay {
  opacity: 1;
}

.quick-add-btn {
  background: white;
  color: #1a8754;
}

.quick-add-btn:hover {
  background: #f0f0f0;
}

.product-info {
  padding: 20px;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
  flex: 1;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.rating-text {
  font-size: 12px;
  color: #ff9900;
  font-weight: 600;
}

.product-desc {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.price-section {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 14px;
}

.current-price {
  font-size: 20px;
  font-weight: 700;
  color: #ff4d4f;
}

.product-actions {
  display: flex;
  gap: 8px;
}

.add-cart-btn,
.detail-btn {
  flex: 1;
  height: 36px;
}

.add-cart-btn {
  background: #1a8754;
  border: none;
}

.add-cart-btn:hover {
  background: #156c43;
}

/* 产品详情弹窗 */
.product-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.product-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.product-detail-main {
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 30px;
  padding: 30px;
  border-bottom: 1px solid #f0f0f0;
}

.product-gallery {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.main-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 8px;
}

.product-detail-info {
  padding: 0;
}

.product-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.product-rating-large {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.review-count {
  color: #666;
  font-size: 14px;
}

.price-section-large {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
}

.original-price-large {
  font-size: 18px;
  color: #999;
  text-decoration: line-through;
}

.current-price-large {
  font-size: 28px;
  font-weight: 700;
  color: #ff4d4f;
}

.discount-tag {
  background: #ff4d4f;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.product-specs {
  margin-bottom: 24px;
}

.spec-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.spec-label {
  width: 60px;
  color: #666;
  font-size: 14px;
}

.spec-value {
  color: #333;
  font-size: 14px;
}

.product-actions-large {
  display: flex;
  gap: 12px;
}

.buy-btn {
  flex: 1;
  height: 48px;
  background: #1a8754;
  border: none;
  font-size: 16px;
}

.buy-btn:hover {
  background: #156c43;
}

.quick-buy-btn {
  flex: 1;
  height: 48px;
  background: #ff4d4f;
  border: none;
  font-size: 16px;
}

.quick-buy-btn:hover {
  background: #d9363e;
}

/* 农夫信息 */
.farmer-section {
  padding: 30px;
}

.farmer-card {
  display: flex;
  gap: 20px;
  align-items: flex-start;
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.farmer-avatar img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.farmer-info {
  flex: 1;
}

.farmer-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.farmer-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-label {
  color: #666;
  font-size: 14px;
  min-width: 80px;
}

.stat-value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.farmer-desc {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

/* 购物车 */
.cart-content {
  padding: 20px;
}

.empty-cart {
  text-align: center;
  padding: 60px 20px;
}

.empty-cart-icon {
  font-size: 64px;
  color: #ccc;
  margin-bottom: 20px;
}

.empty-cart-text {
  color: #666;
  margin-bottom: 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cart-item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
}

.cart-item-info {
  flex: 1;
}

.cart-item-name {
  margin: 0 0 6px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.cart-item-price {
  margin: 0;
  color: #ff4d4f;
  font-weight: 600;
}

.cart-item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-btn {
  width: 28px;
  height: 28px;
  min-width: 28px;
}

.quantity-display {
  font-weight: 600;
  min-width: 30px;
  text-align: center;
}

.cart-total {
  margin: 24px 0;
  padding-top: 20px;
  border-top: 2px solid #f0f0f0;
}

.total-line {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #666;
}

.main-total {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.final-price {
  color: #ff4d4f;
  font-size: 20px;
}

.checkout-btn {
  width: 100%;
  height: 48px;
  background: #1a8754;
  border: none;
  font-size: 16px;
}

.checkout-btn:hover {
  background: #156c43;
}

/* 页脚 */
.market-footer {
  background: #2c3e50;
  color: white;
  margin-top: 60px;
}

.footer-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px 20px;
}

.footer-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 40px;
  margin-bottom: 40px;
}

.footer-section h3,
.footer-section h4 {
  margin-bottom: 16px;
}

.footer-title {
  font-size: 20px;
  font-weight: 700;
  color: #1a8754;
}

.footer-desc {
  color: #bdc3c7;
  line-height: 1.6;
}

.footer-subtitle {
  font-size: 16px;
  font-weight: 600;
  color: #ecf0f1;
}

.footer-links {
  list-style: none;
  padding: 0;
  margin: 0;
}

.footer-links li {
  margin-bottom: 8px;
}

.footer-link {
  color: #bdc3c7;
  text-decoration: none;
  transition: color 0.3s ease;
}

.footer-link:hover {
  color: #1a8754;
}

.footer-bottom {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #34495e;
  color: #95a5a6;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.3;
}

.empty-text {
  color: #666;
  font-size: 16px;
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    flex-direction: column;
    height: auto;
    padding: 16px 20px;
    gap: 16px;
  }
  
  .search-section {
    margin: 0;
    max-width: none;
  }
  
  .carousel-content {
    position: relative;
    right: auto;
    top: auto;
    transform: none;
    max-width: none;
    margin: 20px;
  }
  
  .menu-level-1 {
    flex-direction: column;
  }
  
  .tree-selector-container {
    position: static;
    box-shadow: none;
    border: none;
    padding: 16px 0;
  }
  
  .content-container {
    padding: 20px;
  }
  
  .products-grid {
    grid-template-columns: 1fr;
  }
  
  .product-detail-main {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .farmer-card {
    flex-direction: column;
    text-align: center;
  }
  
  .footer-content {
    grid-template-columns: 1fr;
    gap: 30px;
  }
}

@media (max-width: 480px) {
  .nav-container {
    padding: 16px;
  }
  
  .content-container {
    padding: 16px;
  }
  
  .carousel-title {
    font-size: 22px;
  }
}
</style>